<template>
    <div class="orgEditor outBox">
        <Row style="margin-top:10px;margin-bottom:10px;">
            <Col span="17">
                <Button class="ivu-btn-default" @click="createRootNode">创建一级部门</Button>
                <Button class="ivu-btn-default" @click="save">保存草稿</Button>
                <Button class="ivu-btn-default" @click="submit">提交</Button>
            </Col>
        </Row>
        <div style="width: 100%; display: flex; justify-content: space-between;flex: 1;">
            <div ref="diagram" style="flex-grow: 1;"></div>
            <div>
                <div>
                    <Form ref="orgForm" v-show="orgEditorShow" :model="selectedOrg" :rules="orgValidateRule"
                          :label-width="80">
                        <FormItem label="部门" prop="organization">
                            <Input placeholder="请输入部门名称" ref="orgName" v-model="selectedOrg.organization"
                                   @on-blur="validateSelectedNode"></Input>
                        </FormItem>
                        <FormItem label="职位" prop="position">
                            <AutoComplete
                                    ref="userPosition"
                                    v-model="selectedOrg.position"
                                    @on-search="searchPosition"
                                    @on-select="selectPosition"
                                    placeholder="请输入职位"
                                    style="width:200px">
                                <Option v-for="item in positionList" :value="item.name" :key="item.id">{{ item.name }}
                                </Option>
                            </AutoComplete>
                        </FormItem>
                        <FormItem label="姓名" prop="name">
                            <AutoComplete ref="userName"
                                          v-model="selectedOrg.name"
                                          @on-search="searchUser"
                                          @on-select="selectUser"
                                          placeholder="请输入姓名"
                                          style="width:200px">
                                <Option v-for="item in userList" :value="item.name" :key="item.id">{{ item.name }}
                                </Option>
                            </AutoComplete>
                        </FormItem>
                        <FormItem label="手机号" prop="mobile">
                            <Input ref="userMobile" placeholder="请输入手机号" v-model="selectedOrg.mobile"
                                   @on-blur="validateSelectedNode"
                                   :disabled="mobileDisable"></Input>
                        </FormItem>
                    </Form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import go from 'gojs';

    var $ = go.GraphObject.make;
    var nodeIdCounter = -1; // use a sequence to guarantee key uniqueness as we add/remove/modify nodes
    export default {
        name: 'departmentMaintenance',
        props: {
    
        },
        data () {
            return {
                diagram: null,
                userEditorVisible: false,
                inspectedObject: null,
                blankOrg:
                    {
                        organization: '',
                        position: '',
                        name: '',
                        mobile: ''
                    },
                selectedOrg:
                    {
                        organization: '',
                        position: '',
                        name: '',
                        mobile: ''
                    },
                orgValidateRule: {
                    organization: {validator: this.validateOrganizationInForm, trigger: 'blur'},
                    position: {validator: this.validatePositionInForm, trigger: 'blur'},
                    name: {validator: this.validateNameInForm, trigger: 'blur'},
                    mobile: {validator: this.validateMobileInForm, trigger: 'blur'}
                },
                orgEditorShow: false,
                positionList: [],
                positionDbList: [],
                userList: [],
                userDbList: [],
                diagramData: {
                    'class': 'go.TreeModel',
                    'nodeDataArray': []
                },
                mobileDisable: false,
                errorMsg: null,
                focusField: null,
                mobileReg: /^[1][0-9]{10}$/,
                orgReg: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                positionReg: /^[a-zA-Z0-9_&\u4e00-\u9fa5]+$/,
                nameReg: /^[·\u4e00-\u9fa5]+$/,
                version: 0
            };
        },
        mounted () {
            var self = this;
            this.initData();
    
            var myDiagram =
                $(go.Diagram, this.$refs.diagram,
                    {
                        initialContentAlignment: go.Spot.Center,
                        maxSelectionCount: 1, // users can select only one part at a time,
                        validCycle: go.Diagram.CycleDestinationTree, // make sure users can only create trees
                        'clickCreatingTool.archetypeNodeData': {}, // allow double-click in background to create a new node
                        'clickCreatingTool.insertPart': function (loc) { // customize the data for the new node
                            this.archetypeNodeData = {
                                key: this.getNextKey(), // assign the key based on the number of nodes
                                position: '职位',
                                title: ''
                            };
                            return go.ClickCreatingTool.prototype.insertPart.call(this, loc);
                        },
                        layout:
                            $(go.TreeLayout,
                                {
                                    treeStyle: go.TreeLayout.StyleLastParents,
                                    arrangement: go.TreeLayout.ArrangementHorizontal,
                                    // properties for most of the tree:
                                    angle: 90,
                                    layerSpacing: 35,
                                    // properties for the "last parents":
                                    alternateAngle: 90,
                                    alternateLayerSpacing: 35,
                                    alternateAlignment: go.TreeLayout.AlignmentBus,
                                    alternateNodeSpacing: 20
                                }),
                        'undoManager.isEnabled': true // enable undo & redo
                    });

            myDiagram.addDiagramListener('ChangedSelection', function (e) {
                self.inspectObject();
            });
            // var levelColors = ["#AC193D/#BF1E4B", "#2672EC/#2E8DEF", "#8C0095/#A700AE", "#5133AB/#643EBF",
            //     "#008299/#00A0B1", "#D24726/#DC572E", "#008A00/#00A600", "#094AB2/#0A5BC4"];
            var levelColors = ['#2672EC/#2E8DEF', '#8C0095/#A700AE', '#5133AB/#643EBF',
                '#008299/#00A0B1', '#D24726/#DC572E', '#008A00/#00A600', '#094AB2/#0A5BC4'];
            // override TreeLayout.commitNodes to also modify the background brush based on the tree depth level
            myDiagram.layout.commitNodes = function () {
                go.TreeLayout.prototype.commitNodes.call(myDiagram.layout); // do the standard behavior
                // then go through all of the vertexes and set their corresponding node's Shape.fill
                // to a brush dependent on the TreeVertex.level value
                myDiagram.layout.network.vertexes.each(function (v) {
                    if (v.node) {
                        var level = v.level % (levelColors.length);
                        var colors = levelColors[level].split('/');
                        v.node.colors = colors;
                        // if (v.node && v.node.data && v.node.hasError) {
                        //     colors = ["#AC193D", "#BF1E4B"];
                        // }
                        var shape = v.node.findObject('SHAPE');
                        if (shape) {
                            shape.fill = $(go.Brush, 'Linear', {
                                0: colors[0],
                                1: colors[1],
                                start: go.Spot.Left,
                                end: go.Spot.Right
                            });
                        }
                    }
                });
            };

            // define the Node template
            myDiagram.nodeTemplate =
                $(go.Node, 'Auto',
                    { // handle dragging a Node onto a Node to (maybe) change the reporting relationship
                        mouseDragEnter: function (e, node, prev) {
                            var diagram = node.diagram;
                            var selnode = diagram.selection.first();
                            if (!mayWorkFor(selnode, node)) return;
                            var shape = node.findObject('SHAPE');
                            if (shape) {
                                shape._prevFill = shape.fill; // remember the original brush
                                shape.fill = 'darkred';
                            }
                        },
                        mouseDragLeave: function (e, node, next) {
                            var shape = node.findObject('SHAPE');
                            if (shape && shape._prevFill) {
                                shape.fill = shape._prevFill; // restore the original brush
                            }
                        },
                        mouseDrop: function (e, node) {
                            var diagram = node.diagram;
                            var selnode = diagram.selection.first(); // assume just one Node in selection
                            if (mayWorkFor(selnode, node)) {
                                // find any existing link into the selected node
                                var link = selnode.findTreeParentLink();
                                if (link !== null) { // reconnect any existing link
                                    link.fromNode = node;
                                } else { // else create a new link
                                    diagram.toolManager.linkingTool.insertLink(node, node.port, selnode, selnode.port);
                                }
                            }
                        }
                    },
                    // for sorting, have the Node.text be the data.name
                    new go.Binding('text', 'position'),
                    // bind the Part.layerName to control the Node's layer depending on whether it isSelected
                    new go.Binding('layerName', 'isSelected', function (sel) {
                        return sel ? 'Foreground' : '';
                    }).ofObject(),
                    // define the node's outer shape
                    $(go.Shape, 'Rectangle',
                        {
                            name: 'SHAPE',
                            fill: 'white',
                            stroke: null,
                            // set the port properties:
                            portId: '',
                            fromLinkable: true,
                            toLinkable: true,
                            cursor: 'pointer'
                        }
                    ),
                    $(go.Panel, 'Horizontal',
                        $(go.Picture,
                            {
                                name: 'Picture',
                                desiredSize: new go.Size(39, 50),
                                margin: new go.Margin(6, 8, 6, 10)
                            },
                            new go.Binding('source', 'key', this.findHeadShot)),
                        // define the panel where the text will appear
                        $(go.Panel, 'Table',
                            {
                                maxSize: new go.Size(230, 999),
                                margin: new go.Margin(6, 8, 6, 10),
                                defaultAlignment: go.Spot.Left
                            },
                            $(go.RowColumnDefinition, {column: 2, width: 1}),
                            $(go.TextBlock, this.textStyle(), // the name
                                {
                                    row: 0,
                                    column: 0,
                                    columnSpan: 2,
                                    font: '12pt Segoe UI,sans-serif',
                                    editable: false,
                                    isMultiline: false,
                                    minSize: new go.Size(10, 16)
                                },
                                new go.Binding('text', 'organization').makeTwoWay()),
                            $(go.TextBlock, '职位: ', this.textStyle(),
                                {row: 1, column: 0}),
                            $(go.TextBlock, this.textStyle(),
                                {
                                    row: 1,
                                    column: 1,
                                    editable: false,
                                    isMultiline: false,
                                    minSize: new go.Size(10, 14),
                                    margin: new go.Margin(0, 0, 0, 3)
                                },
                                new go.Binding('text', 'position').makeTwoWay()),
                            $(go.TextBlock, '姓名: ', this.textStyle(),
                                {row: 3, column: 0}),
                            $(go.TextBlock, this.textStyle(),
                                {
                                    row: 3,
                                    column: 1,
                                    editable: false,
                                    isMultiline: false,
                                    minSize: new go.Size(10, 14),
                                    margin: new go.Margin(0, 0, 0, 3)
                                },
                                new go.Binding('text', 'name').makeTwoWay())
                        ) // end Table Panel
                    ) // end Horizontal Panel
                ); // end Node

            // the context menu allows users to make a position vacant,
            // remove a role and reassign the subtree, or remove a organization
            myDiagram.nodeTemplate.contextMenu =
                $(go.Adornment, 'Vertical',
                    $('ContextMenuButton',
                        $(go.TextBlock, '创建子部门'),
                        {
                            click: function (e, obj) {
                                var node = obj.part.adornedPart;
                                if (node !== null) {
                                    var thisemp = node.data;
                                    myDiagram.startTransaction('createDepartmentOrPosition');
                                    var newemp = {
                                        key: self.getNextKey(),
                                        'organization': '',
                                        'position': '',
                                        'name': '',
                                        'mobile': '',
                                        nodeType: 'department',
                                        parent: thisemp.key,
                                        isSelected: true
                                    };
                                    myDiagram.model.addNodeData(newemp);
                                    myDiagram.select(myDiagram.findNodeForKey(newemp.key));
                                    myDiagram.commitTransaction('createDepartmentOrPosition');
                                }
                            }
                        }
                    ),
                    $('ContextMenuButton',
                        $(go.TextBlock, '创建职位'),
                        {
                            click: function (e, obj) {
                                var node = obj.part.adornedPart;
                                if (node !== null) {
                                    var thisemp = node.data;
                                    myDiagram.startTransaction('createDepartmentOrPosition');
                                    var newemp = {
                                        key: self.getNextKey(),
                                        'organization': thisemp.organization,
                                        'organizationId': thisemp.organizationId,
                                        'position': '',
                                        'name': '',
                                        'mobile': '',
                                        nodeType: 'position',
                                        parent: thisemp.key,
                                        isSelected: true
                                    };
                                    myDiagram.model.addNodeData(newemp);
                                    myDiagram.select(myDiagram.findNodeForKey(newemp.key));
                                    myDiagram.commitTransaction('createDepartmentOrPosition');
                                }
                            }
                        }
                    ),
                    $('ContextMenuButton',
                        $(go.TextBlock, '复制'),
                        {
                            click: function (e, obj) {
                                var node = obj.part.adornedPart;
                                if (node !== null) {
                                    var thisemp = node.data;
                                    myDiagram.startTransaction('createDepartmentOrPosition');
                                    var newemp = {
                                        key: self.getNextKey(),
                                        'organization': thisemp['organization'],
                                        'organizationId': thisemp['organizationId'],
                                        'position': thisemp['position'],
                                        'positionId': thisemp['positionId'],
                                        'name': thisemp['name'],
                                        'userId': thisemp['userId'],
                                        'mobile': thisemp['mobile'],
                                        nodeType: thisemp['nodeType'],
                                        parent: thisemp.parent
                                    };
                                    myDiagram.model.addNodeData(newemp);
                                    myDiagram.select(myDiagram.findNodeForKey(newemp.key));
                                    myDiagram.commitTransaction('createDepartmentOrPosition');
                                }
                            }
                        }
                    ),
                    $('ContextMenuButton',
                        $(go.TextBlock, '清空'),
                        {
                            click: function (e, obj) {
                                // remove the whole subtree, including the node itself
                                var node = obj.part.adornedPart;
                                if (node !== null) {
                                    myDiagram.startTransaction('reset dept');
                                    var thisemp = node.data;
                                    self.selectedOrg = {
                                        key: thisemp.key,
                                        'organization': '',
                                        'organizationId': thisemp.organizationId,
                                        'position': '',
                                        'name': '',
                                        'mobile': '',
                                        nodeType: thisemp.position,
                                        parent: thisemp.parent,
                                        isSelected: true
                                    };
                                    myDiagram.commitTransaction('reset dept');
                                }
                                // 自动保存
                                localStorage.setItem('diagramData', myDiagram.model.toJson());
                            }
                        }
                    ),
                    $('ContextMenuButton',
                        $(go.TextBlock, '删除'),
                        {
                            click: function (e, obj) {
                                // remove the whole subtree, including the node itself
                                var node = obj.part.adornedPart;
                                if (node !== null) {
                                    if (!node.isTreeLeaf) {
                                        self.$Modal.confirm({
                                            title: '确认',
                                            content: '将删除' + node.data.organization + '和其下所有部门和职位，是否确认删除？',
                                            onOk: () => {
                                                myDiagram.startTransaction('remove dept');
                                                myDiagram.removeParts(node.findTreeParts());
                                                self.selectedOrg = self.blankOrg;
                                                myDiagram.commitTransaction('remove dept');
                                            },
                                            onCancel: () => {
    
                                            }
                                        });
                                    } else {
                                        myDiagram.startTransaction('remove dept');
                                        myDiagram.removeParts(node.findTreeParts());
                                        self.selectedOrg = self.blankOrg;
                                        myDiagram.commitTransaction('remove dept');
                                    }
                                }
                                // 自动保存
                                localStorage.setItem('diagramData', myDiagram.model.toJson());
                            }
                        }
                    )
                );
            // define the Link template
            myDiagram.linkTemplate =
                $(go.Link, go.Link.Orthogonal,
                    {corner: 5, relinkableFrom: true, relinkableTo: true},
                    $(go.Shape, {strokeWidth: 4, stroke: '#00a4a4'})); // the link shape
            myDiagram.linkTemplate.contextMenu =
                $(go.Adornment, 'Vertical',
                    $('ContextMenuButton',
                        $(go.TextBlock, '删除关联'),
                        {
                            click: function (e, obj) {
                                var link = obj.part.adornedPart;
                                // console.log(link)
                                // myDiagram.startTransaction("remove link");
                                myDiagram.remove(link);
                                // myDiagram.commitTransaction("remove link");
                                // myDiagram.commandHandler.deleteSelection();
                                // e.diagram.commandHandler.deleteSelection();
                            }
                        },
                        {}
                    )
                );

            this.diagram = myDiagram;

            myDiagram.model = go.Model.fromJson(this.diagramData);
        },
        methods: {
            initData () {
                // 获取组织图
                var diagramDataCache = localStorage.getItem('diagramData');
                if (diagramDataCache) {
                    // this.$Modal.confirm({
                    //     title: '确认',
                    //     content: '您上次编辑的内容尚未提交，是否继续编辑？',
                    //     okText: '继续编辑',
                    //     cancelText: '放弃草稿',
                    //     onOk: () => {
                    //         this.diagramData = JSON.parse(diagramDataCache);
                    //         this.diagram.model = go.Model.fromJson(this.diagramData);
                    //     },
                    //     onCancel: () => {
                    //         this.loadGraphicData();
                    //     }
                    // });
                } else {
                    this.loadGraphicData();
                }
                // 获取职位信息
                depot.get({
                    url: this.URL.USER.FIND_POSITION_LIST,
                    cb: (data) => {
                        if (data.code === 0) {
                            this.positionDbList = data.data;
                        } else if (data.code === 999) {
                            this.$Message.error(data.message);
                        }
                    }
                });

                // 获取员工信息
                depot.get({
                    url: this.URL.USER.FIND_USER_LIST,
                    cb: (data) => {
                        if (data.code === 0) {
                            this.userDbList = data.data;
                        } else if (data.code === 999) {
                            this.$Message.error(data.message);
                        }
                    }
                });
            },
            loadGraphicData () {
                depot.get({
                    url: this.URL.USER.FIND_GRAPHIC_DATA,
                    cb: (data) => {
                        if (data.code === 0) {
                            if (!!data.data && !!data.data.context) {
                                var graphicData = JSON.parse(data.data.context);
                                this.version = data.data.version ? data.data.version : 0;
                                this.diagramtData = graphicData;
                                this.diagram.model = go.Model.fromJson(this.diagramtData);
                            }
                        } else if (data.code === 999) {
                            this.$Message.error(data.message);
                        }
                    }
                });
            },
            save () {
                // 保存组织架构图
                localStorage.setItem('diagramData', this.diagram.model.toJson());
                this.$Message.success('保存成功');
            },
            submit () {
                if (this.validateOrg()) {
                    let submitData = null;
                    if (this.diagram.model && this.diagram.model.toJson()) {
                        submitData = JSON.parse(this.diagram.model.toJson());
                        submitData.version = this.version;
                    }
                    // 提交组织架构图
                    depot.post({
                        url: this.URL.USER.ADD_ORGANIZATION_STRUCTURE,
                        data: JSON.stringify(submitData),
                        cb: (data) => {
                            if (data.code === 0) {
                                this.$Message.success('提交成功');
                                // 重新加载图数据
                                this.loadGraphicData();
                                this.orgEditorShow = false;
                                // 删除草稿
                                localStorage.removeItem('diagramData');
                            } else {
                                this.$Message.error(data.message);
                            }
                        }
                    });
                }
            },
            // 校验组织架构
            validateOrg () {
                var orgDataStr = this.diagram.model.toJson();
                if (!orgDataStr) {
                    this.$Message.error('组织架构信息不能为空！');
                    return false;
                }
                var orgData = JSON.parse(orgDataStr);
                var nodeList = orgData.nodeDataArray;
                if (!nodeList || nodeList.length < 1) {
                    this.$Message.error('组织架构信息不能为空！');
                    return false;
                }
                var firstErrorKey = null;
                this.errorMsg = null;
                this.focusField = null;
                nodeList.forEach(node => {
                    if (!this.validateNode(this.diagram.findNodeForKey(node.key))) {
                        firstErrorKey = firstErrorKey == null ? node.key : firstErrorKey;
                    }
                });

                if (firstErrorKey != null) {
                    if (this.errorMsg) {
                        this.$Message.error(this.errorMsg);
                        this.diagram.select(this.diagram.findNodeForKey(firstErrorKey));
                        this.$refs[this.focusField].focus();
                    }
                    return false;
                }
                return true;
            },
            // This function is used to find a suitable ID when modifying/creating nodes.
            // We used the counter combined with findNodeDataForKey to ensure uniqueness.
            getNextKey () {
                var key = nodeIdCounter;
                while (this.diagram.model.findNodeDataForKey(key) !== null) {
                    key = nodeIdCounter++;
                }
                return key;
            },
            // 编辑
            edit (e, obj) {
            },
            // This function provides a common style for most of the TextBlocks.
            // Some of these values may be overridden in a particular TextBlock.
            textStyle () {
                return {font: '9pt  Segoe UI,sans-serif', stroke: 'white'};
            },
            // This converter is used by the Picture.
            findHeadShot (key) {
                if (key < 0 || key > 16) return 'http://192.168.0.10/images/HSnopic.png'; // There are only 16 images on the server
                return 'http://192.168.0.10/images/HSnopic.png';
            },
            inspectObject (object) {
                // 自动保存
                localStorage.setItem('diagramData', this.diagram.model.toJson());
                var inspectedObject = null;
                if (object === null) return;
                if (object === undefined) {
                    inspectedObject = this.diagram.selection.first();
                } else { // if object was passed in as a parameter
                    inspectedObject = object;
                }
                if (inspectedObject === null || this.inspectedObject === inspectedObject) {
                    this.inspectedObject = inspectedObject;
                    this.orgEditorShow = false;
                    this.selectedOrg = this.blankOrg;
                    return;
                }
                this.inspectedObject = inspectedObject;
                if (this.inspectObject === null) return;
                var data = (inspectedObject instanceof go.Part) ? inspectedObject.data : inspectedObject;
                if (!data) return;

                if (inspectedObject instanceof go.Node) {
                    this.orgEditorShow = true;
                    // this.selectedOrg = data;
                    this.selectedOrg['organization'] = data['organization'];
                    this.selectedOrg['position'] = data['position'];
                    this.selectedOrg['name'] = data['name'];
                    this.selectedOrg['mobile'] = data['mobile'];
                    this.$refs['orgForm'].validate((valid) => {
                    });
                } else {
                    this.selectedOrg = this.blankOrg;
                    this.orgEditorShow = false;
                }
            },
            setNodeValue (key, value) {
                if (!this.selectedOrg) {
                    return;
                }
                if (!this.diagramData) {
                    return;
                }
                this.inspectedObject = this.diagram.selection.first();
                var isPart = this.inspectedObject instanceof go.Part;
                var data = isPart ? this.inspectedObject.data : this.inspectedObject;
                if (!data) { return; } // must not try to update data when there's no data!
                this.diagram.model.setDataProperty(data, key, value);
                // 设置组织名称时，校验组织名称与父组织名称是否一致，是一致时，更新nodeType为department
                if (key == 'organization') {
                    var parentNode = this.diagram.findNodeForKey(data.parent);
                    if (parentNode && parentNode.data) {
                        var parentNodeData = parentNode.data;
                        if (parentNodeData.organization && parentNodeData.organization == value) {
                            this.diagram.model.setDataProperty(data, 'nodeType', 'position');
                        } else {
                            this.diagram.model.setDataProperty(data, 'nodeType', 'department');
                        }
                    }
                }
            },
            createRootNode () {
                this.diagram.startTransaction('createDepartmentOrPosition');
                var newemp = {
                    key: this.getNextKey(),
                    'organization': '',
                    'position': '',
                    'name': '',
                    'mobile': '',
                    'nodeType': 'department'
                };
                this.diagram.model.addNodeData(newemp);
                this.diagram.commitTransaction('createDepartmentOrPosition');
            },
            searchPosition (value) {
                this.positionList = [];
                if (this.positionDbList) {
                    this.positionDbList.forEach(position => {
                        if (position.name) {
                            if (!!value && position.name.indexOf(value) == 0) {
                                this.positionList.push(position);
                            }
                        }
                    });
                    if (this.positionList.length == 0) {
                        this.setNodeValue('positionId', null);
                    }
                    if (this.positionList.length == 1) {
                        var position = this.positionList[0];
                        if (position.name === value) {
                            this.positionList = [];
                            this.setNodeValue('positionId', position.id);
                        }
                    }
                }
            },
            selectPosition (obj) {
                this.setNodeValue('position', obj);
                if (this.positionList) {
                    this.positionList.forEach(position => {
                        if (position.name) {
                            if (position.name === obj) {
                                this.setNodeValue('positionId', position.id);
                            }
                        }
                    });
                }
            },
            searchUser (value) {
                this.mobileDisable = false;
                this.userList = [];
                if (this.userDbList) {
                    this.userDbList.forEach(user => {
                        if (user.name) {
                            if (!!value && user.name.indexOf(value) == 0) {
                                this.userList.push(user);
                            }
                        }
                    });
                    if (this.userList.length == 0) {
                        this.setNodeValue('userId', null);
                    }
                    if (this.userList.length == 1) {
                        var user = this.userList[0];
                        if (user.name === value) {
                            this.userList = [];
                            this.setNodeValue('userId', user.id);
                            this.selectedOrg['mobile'] = user['mobile'];
                            this.mobileDisable = true;
                        }
                    }
                }
            },
            selectUser (obj) {
                this.setNodeValue('name', obj);
                if (this.userList) {
                    this.userList.forEach(user => {
                        if (user.name) {
                            if (user.name === obj) {
                                this.setNodeValue('userId', user.id);
                                this.selectedOrg['mobile'] = user['mobile'];
                                this.mobileDisable = true;
                            }
                        }
                    });
                }
            },
            setNodeColor (node, colors) {
                if (!node) return;
                var shape = node.findObject('SHAPE');
                if (shape) {
                    shape.fill = $(go.Brush, 'Linear', {
                        0: colors[0],
                        1: colors[1],
                        start: go.Spot.Left,
                        end: go.Spot.Right
                    });
                }
            },
            validateSelectedNode () {
                this.validateNode(this.inspectedObject);
            },
            validateNode (node) {
                var nodeValidateFlag = true;
                if (node) {
                    if (this.validateOrganization(node.data.organization, node, null) &&
                        this.validatePosition(node.data.position, node, null) &&
                        this.validateName(node.data.name, node, null) &&
                        this.validateMobile(node.data.mobile, node, null)) {
                        // this.setNodeColor(node, node.colors);
                    } else {
                        // this.setNodeColor(node, ["#AC193D", "#BF1E4B"]);
                        nodeValidateFlag = false;
                    }
                    if (node.isSelected) {
                        this.$refs['orgForm'].validate((valid) => {
                        });
                    }
                } else {
                    nodeValidateFlag = false;
                }
                return nodeValidateFlag;
            },
            validateOrgData (orgData) {
                if (orgData && orgData.trim() != '') {
                    return true;
                } else {
                    if (!this.errorMsg) {
                        this.errorMsg = '请输入部门名称';
                        this.focusField = 'orgName';
                    }
                    return false;
                }
            },
            // 校验表单中的组织
            validateOrganizationInForm (rule, value, callback) {
                this.validateOrganization(value, this.inspectedObject, callback);
            },
            // 校验表单中的手机号
            validateMobileInForm (rule, value, callback) {
                this.validateMobile(value, this.inspectedObject, callback);
            },
            // 校验表单中的职位
            validatePositionInForm (rule, value, callback) {
                this.validatePosition(value, this.inspectedObject, callback);
            },
            // 校验表单中的职位
            validateNameInForm (rule, value, callback) {
                this.validateName(value, this.inspectedObject, callback);
            },
            // 校验组织
            validateOrganization (value, node, callback) {
                if (!node) return false;
                var organization = node.data.organization;
                if (!organization) {
                    if (callback) {
                        callback(new Error('部门为必填项'));
                    }
                    if (!this.errorMsg) {
                        this.errorMsg = '部门为必填项';
                        this.focusField = 'orgName';
                    }
                    return false;
                }
                if (organization && !this.orgReg.test(organization)) {
                    if (callback) {
                        callback(new Error('部门格式不正确'));
                    }
                    if (!this.errorMsg) {
                        this.errorMsg = '部门格式不正确';
                        this.focusField = 'orgName';
                    }
                    return false;
                } else {
                    if (callback) {
                        callback();
                    }
                    return true;
                }
            },
            // 校验职位
            validatePosition (value, node, callback) {
                if (!node) {
                    return false;
                }
                var position = node.data.position;
                if (position && !this.positionReg.test(position)) {
                    if (callback) {
                        callback(new Error('职位格式不正确'));
                    }
                    if (!this.errorMsg) {
                        this.errorMsg = '职位格式不正确';
                        this.focusField = 'userPosition';
                    }
                    return false;
                } else {
                    if (callback) {
                        callback();
                    }
                    return true;
                }
            },
            // 校验名称
            validateName (value, node, callback) {
                if (!node) {
                    return false;
                }
                var name = node.data.name;
                if (name && !this.nameReg.test(name)) {
                    if (callback) {
                        callback(new Error('姓名格式不正确'));
                    }
                    if (!this.errorMsg) {
                        this.errorMsg = '姓名格式不正确';
                        this.focusField = 'userName';
                    }
                    return false;
                } else {
                    if (callback) {
                        callback();
                    }
                    return true;
                }
            },
            // 校验手机号
            validateMobile (value, node, callback) {
                if (!node) return false;
                var mobile = node.data.mobile;

                if (mobile && !this.mobileReg.test(mobile)) {
                    if (callback) {
                        callback(new Error('手机号格式不正确'));
                    }
                    if (!this.errorMsg) {
                        this.errorMsg = '手机号格式不正确';
                        this.focusField = 'userMobile';
                    }
                    return false;
                } else {
                    if (callback) {
                        callback();
                    }
                    return true;
                }
            }
        },
        watch: {
            'selectedOrg.organization' (newValue) {
                this.setNodeValue('organization', newValue);
                // this.validateSelectedNode();
            },
            'selectedOrg.position' (newValue) {
                this.setNodeValue('position', newValue);
            },
            'selectedOrg.name' (newValue) {
                this.setNodeValue('name', newValue);
                // this.validateSelectedNode();
            },
            'selectedOrg.mobile' (newValue) {
                this.setNodeValue('mobile', newValue);
            }
        }
    };
</script>

<style>
    .orgEditor.outBox{
        height: 100%;
        display: flex;
        flex-direction: column;
    }
</style>
